//
//  HomeViewController.m
//  LubanWork
//
//  Created by xiaohao on 2019/12/31.
//  Copyright © 2019 xiaohao. All rights reserved.
//

#import "HomeViewController.h"
#import "HomePageTableViewCell.h"
#import "HomePageCollectionViewCell.h"
#import "CollectionDetailViewController.h"
#import "WorkDetailViewController.h"
#import "SearchBarDisplayCenter.h"
#import "MyCollectionModel.h"
#import "SDCycleScrollView.h"
#import "imageArrayModel.h"
#import "searchViewController.h"
#import "LocationSelectViewController.h"

@interface HomeViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate,SearchBarDisplayCenterDelegate,SDCycleScrollViewDelegate>{
    MJRefreshAutoNormalFooter *footer;
    
}
@property(nonatomic,strong) UITableView * table;
@property(nonatomic,strong) MyCollectionModel * colectionModel;
@property(nonatomic,strong) imageArrayModel * ArrayModel;
@property(nonatomic,strong) UICollectionView * main_clv;
@property(nonatomic,assign) NSInteger page;
@property(nonatomic,copy) NSArray * titleArray;
@property(nonatomic,strong) NSMutableArray * titArray;
@property(nonatomic,copy) NSArray * imgArray;
@property(nonatomic,strong) UISearchBar * searchBar;
@property(nonatomic,strong) NSMutableArray * ImageArray;
@property(nonatomic,strong) NSMutableArray * urlArray;
@end
static NSString *cellID = @"HomePageTableViewCell";
static NSString *cellClvID = @"HomePageCollectionViewCell";
@implementation HomeViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.navigationController.view.backgroundColor = [UIColor whiteColor];
//    self.navigationController.navigationBar.translucent = NO;
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    self.ImageArray = [NSMutableArray array];
    self.urlArray = [NSMutableArray array];
    [self getImageArray];
}
-(void)getImageArray{
    [[NetWorkManager sharedManager] getData:@"api/carousel/getCarousel" parameters:@{} success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([responseObject[@"code"] isEqualToNumber:@200]) {
            self.ArrayModel = [imageArrayModel yy_modelWithJSON:responseObject];
            for (imageArrayModelResult *list in self.ArrayModel.result) {
                [self.ImageArray addObject:list.imageUrl];
                if (![UtilTools isBlankString:list.jumpUrl]) {
                    [self.urlArray addObject:list.jumpUrl];
                }else{
                    [self.urlArray addObject:@""];
                }
            }
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.page = 1;
    self.navigationController.navigationItem.title = @"";
    [self setNavigation];
    //    [self setMian];
    _titArray = [[NSMutableArray alloc] init];
    [self setTable];
    self.titleArray = @[@"附近兼职",@"周末急招",@"高薪兼职",@"宅家玩赚"];
    self.imgArray = @[@"home_nearbyImg",@"home_weekImg",@"home_salary",@"home_house"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLocation) name:@"updateProvice" object:nil];
    [self loadData];
}
-(void)getSearchKeyWord:(NSString *)searchWord
{
    NSLog(@"searchWord = %@",searchWord);
}

-(void)setNavigation{
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 100.0, kSCRATIO(275), 35.0 )];
    btn.backgroundColor = kColorFromRGBHex(0xF1EEFF);
    [btn setImage:[UIImage imageNamed:@"souso"] forState:0];
    [btn setTitle:@"请输入关键字" forState:0];
    ViewRadius(btn, 5);
    [btn setTitleColor:kColorFromRGBHex(0xBAAFFD) forState:UIControlStateNormal];
    btn.titleLabel.font = kFONT(12);
    [btn addTarget:self action:@selector(sousouClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = btn;
    
    UIButton* right =[[UIButton alloc] initWithFrame:CGRectZero];
    right.tintColor=kColorFromRGBHex(0x775ffb);
    if ([UtilTools isBlankString:[AppDelegate shareAppDelegate].province]) {
        [right setImage:[UIImage imageNamed:@"earth"] forState:UIControlStateNormal];
    }else{
        [right setImage:[UIImage imageNamed:@"location"] forState:UIControlStateNormal];
        [right setTitle:[AppDelegate shareAppDelegate].province forState:UIControlStateNormal];
        [right setTitleColor:kColorFromRGBHex(0x775ffb) forState:UIControlStateNormal];
    }
    [right addTarget:self action:@selector(setLocation) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:right];
};
-(void)setMian{
    
    UIImageView *mainImg = [[UIImageView alloc] initWithFrame:CGRectMake(kSCRATIO(25), 10, WIDTH-kSCRATIO(50), 100)];
    mainImg.backgroundColor = [UIColor redColor];
    [self.view addSubview:mainImg];
    UICollectionViewFlowLayout *layo = [[UICollectionViewFlowLayout alloc] init];
    layo.itemSize = CGSizeMake(WIDTH/4, HEIGHT/4);
    layo.minimumLineSpacing = 0;
    layo.minimumInteritemSpacing = 0;
    
    [self.view addSubview:_main_clv];
}
-(UITableView *)table{
    if (!_table) {
        
        _table = [[UITableView alloc] init];
        _table.delegate = self;
        _table.dataSource = self;
        _table.backgroundColor = kColorFromRGB(249, 247, 255);
        _table.separatorStyle = UITableViewCellSeparatorStyleNone;
        _table.mj_header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.page = 1;
            [self loadData];
        }];
//        _table.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//            self.page ++;
//            [weakSelf loadData];
//        }];
        footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreVideo)];
        [footer setTitle:@"正在加载更多..." forState:MJRefreshStateRefreshing];
        [footer setTitle:@"暂无更多" forState:MJRefreshStateNoMoreData];
        footer.stateLabel.font = [UIFont systemFontOfSize:15.0f];
        footer.automaticallyHidden = YES;
        _table.mj_footer = footer;
        
    }
    return _table;
}
-(void)getMoreVideo{
    self.page ++;
    [self loadData];
}
-( void)setTable{
    [self setExtraCellLineHidden:self.table];
    [self.table setSeparatorInset:UIEdgeInsetsZero];
    [self.view addSubview:self.table];
    [self.table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
}
#pragma --mark table delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        return self.titArray.count;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = [NSString stringWithFormat:@"%ld,%ld",[indexPath section],[indexPath row]];
    HomePageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (!cell) {
        cell = [[HomePageTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    if (indexPath.section == 0 ) {
        if (indexPath.row == 0) {
            [cell removeAllSubviews];
            
            tableView.rowHeight = KSCHEIGHT(266);
            SDCycleScrollView *cycleScrollView3 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(kSCRATIO(25), 10, WIDTH-kSCRATIO(50), 100) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
            ViewRadius(cycleScrollView3, 5);
            cycleScrollView3.currentPageDotImage = [UIImage imageNamed:@"pageControlCurrentDot"];
            cycleScrollView3.pageDotImage = [UIImage imageNamed:@"pageControlDot"];
            cycleScrollView3.imageURLStringsGroup = self.ImageArray;
            NSLog(@"图片图片图片图片图片--%@",self.ImageArray);
            [cell addSubview:cycleScrollView3];
            
            self.main_clv.frame = CGRectMake(25, cycleScrollView3.height+20  , WIDTH-50, WIDTH/4);
            [cell addSubview:_main_clv];
            
            
        }
    }else{
        MyCollectionModelResult *list = self.titArray[indexPath.row];
        cell.titLab.text = list.name;
        
        cell.dayLab.text = [list.wagetype isEqualToNumber:@1] == YES ? @"日结":@"月结";
        
        cell.timeLab.text = [list.jobtime isEqualToNumber:@1] == YES ? @"长期":@"短期";
        if ([list.sex isEqualToNumber:@1]) {
            cell.sexLab.text = @"男";
        }else if ([list.sex isEqualToNumber:@2]){
            cell.sexLab.text = @"女";
        }else{
            cell.sexLab.text = @"男女不限";
        }
        cell.priceLab.text = [NSString stringWithFormat:@"%d",[list.wagemax intValue]];
        cell.detaiLab.text=list.jobsite;
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    
    view.backgroundColor = kColorFromRGB(249, 247, 255);
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return kSCRATIO(202);
    }else{
        return kSCRATIO(90);
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }else{
        return 0;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
- (UICollectionView *)main_clv{
    if (!_main_clv) {
        UICollectionViewFlowLayout *layo = [[UICollectionViewFlowLayout alloc] init];
        
        layo.itemSize = CGSizeMake((WIDTH-50)/4, (WIDTH-50)/4);
        layo.minimumLineSpacing = 0;
        layo.minimumInteritemSpacing = 0;
        _main_clv = [[UICollectionView alloc] initWithFrame:CGRectMake(25, 0, WIDTH-50, (WIDTH-50)/4) collectionViewLayout:layo];
        _main_clv.delegate = self;
        _main_clv.dataSource = self;
        _main_clv.backgroundColor = [UIColor clearColor];
        
        _main_clv.scrollEnabled = NO;
        
        [_main_clv registerClass:[HomePageCollectionViewCell class] forCellWithReuseIdentifier:cellClvID];
    }
    return _main_clv;
}
- (void)setExtraCellLineHidden:(UITableView *)tab{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tab setTableFooterView:view];
}
#pragma --mark clv delegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  self.titleArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomePageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellClvID forIndexPath:indexPath];
    cell.imageView.image = [UIImage imageNamed:self.imgArray[indexPath.row]];
    cell.titLab.text = self.titleArray[indexPath.row];
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    CollectionDetailViewController *CollectionDetailVC = [[CollectionDetailViewController alloc] init];
    CollectionDetailVC.indexForPage = indexPath.row+1;
    CollectionDetailVC.navString = self.titleArray[indexPath.row];
    [self.navigationController pushViewController:CollectionDetailVC animated:YES];
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MyCollectionModelResult *list =  self.titArray[indexPath.row];
    WorkDetailViewController *workDetail = [[WorkDetailViewController alloc] init];
    workDetail.sizeWorkHeight = [list.jobdescribe sizeWithFont:[UIFont systemFontOfSize:12]
       constrainedToSize:CGSizeMake(WIDTH -16.0, CGFLOAT_MAX)
           lineBreakMode:NSLineBreakByWordWrapping];

    workDetail.detailID = list.Id;
    [self.navigationController pushViewController:workDetail animated:YES];
    //    NSURL * url4 = [NSURL URLWithString:@"weixin://"];
    //    [[UIApplication sharedApplication] openURL:url4 options:nil completionHandler:^(BOOL success) {
    //
    //    }];
    //    [[UIApplication sharedApplication] openURL:url4 options:@{} completionHandler:^(BOOL success) {
    //
    //    }];
}
-(void)loadData{
    
    [footer setTitle:@"点击或上拉加载更多" forState:MJRefreshStateIdle];
    NSDictionary *dic = @{
        @"pageNo":[NSString stringWithFormat:@"%ld",(long)self.page],
        @"pageSize":@"10",
        @"name":@"",
        @"choice":@"",
        @"jobcategory":@"",
        @"jobsite":([UtilTools isBlankString:[AppDelegate shareAppDelegate].province]?@"":[AppDelegate shareAppDelegate].province),
    };
    __weak typeof(self) weakSelf = self;
    [[NetWorkManager sharedManager]getData:@"api/jianzhi/getJianzhi" parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([responseObject[@"code"]isEqualToNumber:@200]) {
            NSArray *arr = responseObject[@"result"];
            if (weakSelf.page == 1) {
                [weakSelf.titArray removeAllObjects];
            }
            weakSelf.colectionModel = [MyCollectionModel yy_modelWithJSON:responseObject];
            if (arr.count <= 0) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self->footer setTitle:@"暂无更多数据" forState:MJRefreshStateIdle];
                });
                
            }else{
                [weakSelf.titArray addObjectsFromArray:weakSelf.colectionModel.result];
            }
//
            if (self.colectionModel.result.count > 0) {
                [weakSelf.table.mj_footer endRefreshingWithNoMoreData];
            }else{
                
            }
            if (arr == 0) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self->footer setTitle:@"暂无更多" forState:MJRefreshStateIdle];
                });
                
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                          [weakSelf.table reloadData];
                          [weakSelf.table.mj_footer endRefreshing];
                          [weakSelf.table.mj_header endRefreshing];
                      });
//            if (self.colectionModel.result.count <= 0) {
//                
//                [weakSelf.table.mj_footer endRefreshingWithNoMoreData];
//          
//            }else{
//                weakSelf.colectionModel = [MyCollectionModel yy_modelWithJSON:responseObject];
//            }
//              
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [weakSelf.table reloadData];
//                
//                [weakSelf.table.mj_header endRefreshing];
//                [weakSelf.table.mj_footer endRefreshing];
//            });
//            
            
        }else{
            
        }
        //        UserModel *user = [UserModel sharedInstance:UserKey0];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [HWProgressHUD showMessage:@"请联系管理员"];
            [weakSelf.table.mj_header endRefreshing];
            [weakSelf.table.mj_footer endRefreshing];
        });
        
    }];
}
-(void)selectSearch{
    searchViewController *sVC = [[searchViewController alloc] init];
    [self.navigationController pushViewController:sVC animated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat sectionHeaderHeight = 44;//这里的高度是设置的sectionView的高度
    
    if(scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        
    } else if (scrollView.contentOffset.y >= sectionHeaderHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
//    if (scrollView.contentOffset.y > kNavHeight) {
//        [self.navigationController setNavigationBarHidden:YES animated:YES];
//    }else{
//        [self.navigationController setNavigationBarHidden:NO animated:YES];
//    }
    
}

-(void)sousouClick{
    searchViewController *searchVC = [[searchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}

-(void)setLocation{
    [self.navigationController pushViewController:[LocationSelectViewController new] animated:YES];
}

-(void)updateLocation{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIButton* right =[[UIButton alloc] initWithFrame:CGRectZero];
        right.tintColor=kColorFromRGBHex(0x775ffb);
        if ([UtilTools isBlankString:[AppDelegate shareAppDelegate].province]) {
            [right setImage:[UIImage imageNamed:@"earth"] forState:UIControlStateNormal];
        }else{
            [right setImage:[UIImage imageNamed:@"location"] forState:UIControlStateNormal];
            [right setTitle:[AppDelegate shareAppDelegate].province forState:UIControlStateNormal];
            [right setTitleColor:kColorFromRGBHex(0x775ffb) forState:UIControlStateNormal];
        }
        [right addTarget:self action:@selector(setLocation) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:right];
        self.page = 1;
        [self loadData];
    });
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.urlArray[index]] options:@{} completionHandler:nil];
}

@end
